﻿using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using System.Drawing;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using Polygon = Esri.ArcGISRuntime.Geometry.Polygon;
using Button = System.Windows.Controls.Button;
using System.Timers;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using System.Drawing.Drawing2D;
using System.IO;
using CheckBox = System.Windows.Controls.CheckBox;

namespace classTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        enum CURRENTOPERATION
        {
            IdentifyQuery,
            None,
            Roam,
            ZoomEnv,
            StartTextBox,
            EndTextBox,
                ViaTextBox,
        };

        private List<MapPoint> linePoints = new List<MapPoint>();  // 矩形框选范围用
        private System.Windows.Controls.CheckBox rightButton_name;
        private FeatureLayer P_featureLayer;    // 当前操作图层
        public MapPoint location;
        private Boolean isLoad = false;

        CURRENTOPERATION m_CurOper=CURRENTOPERATION.None;

        //识别查询
        private Boolean iqwIsExist = false;
        IdentifyQueryWindow iqw = null;
        private MapPoint identifyPoint;

        //路径分析
        private SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Blue, 20.0);
        private Graphic startGraphic;
        private Graphic endGraphic;
        private MapPoint fromPoint;
        private MapPoint toPoint;
        public string networkPath;
        public string networkName;
        private Graphic routeGraphic;
        private List<Stop> viaStops = new List<Stop>();
        private GraphicsOverlay _routeGraphicsOverlay = new GraphicsOverlay();
        private GraphicsOverlay _siteGraphicsOverlay = new GraphicsOverlay();
        private List<Graphic> listOfClipGraphics = new List<Graphic>(); //几何操作时选择的图形

        public List<Feature> FeatureQuery = new List<Feature>();

        // 专题地图
        private GraphicsOverlay _pieGraphicsOverlay = new GraphicsOverlay();

        System.Timers.Timer t = new System.Timers.Timer(3000);  // 定义定时器，方便自动调用
        public MainWindow()
        {
            InitializeComponent();

            MyMapView.GraphicsOverlays.Add(_routeGraphicsOverlay);
            MyMapView.GraphicsOverlays.Add(_pieGraphicsOverlay);
            MyMapView.GraphicsOverlays.Add(_siteGraphicsOverlay);
            isLoad = true;
        }
        // 1、文件管理功能：打开在线数据、打开本地数据（shp、Geodatabse）、打开Tif数据、退出。

        // 怎么导出呢？
        private void SaveShp()
        {

        }

        //路径查询  框显示
        private void RouteQuery_Click(object sender, RoutedEventArgs e)
        {
            if (networkPath == null)
            {
                MessageBox.Show("请先设置网络数据集路径");
                return;
            }
            routeBox.Visibility = Visibility.Visible;
        }
        //起点输入框聚焦
        private void StartTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            m_CurOper = CURRENTOPERATION.StartTextBox;

        }
        //终点输入框
        private void EndTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            m_CurOper = CURRENTOPERATION.EndTextBox;
        }
        //途经点输入框
        private void ViaTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            viaStops.Clear();
            m_CurOper = CURRENTOPERATION.ViaTextBox;
            _routeGraphicsOverlay.Graphics.Clear();
            if(startGraphic != null&&startTextBox.Text.First().ToString()!="请")_routeGraphicsOverlay.Graphics.Add(startGraphic);
            if(endGraphic != null&&endTextBox.Text.First().ToString() != "请") _routeGraphicsOverlay.Graphics.Add(endGraphic);
    }
        // 加载路线
        private async void LoadRoute_Click(object sender, RoutedEventArgs e)
        {
            m_CurOper = CURRENTOPERATION.None;
            List<Stop> routeStops = new List<Stop>();
            try
            {
                RouteTask solveRouteTask = await RouteTask.CreateAsync(networkPath, networkName);
                RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();
                routeParams.ReturnStops = true;
                routeParams.ReturnDirections = true;
                if (fromPoint == null && toPoint == null) return;
                Stop stop1 = new Stop(fromPoint);
                Stop stop2 = new Stop(toPoint);
                routeStops.Add(stop1);
                routeStops.AddRange(viaStops);
                routeStops.Add(stop2);
                routeParams.SetStops(routeStops);
                RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);
                Route route = solveRouteResult.Routes.First();
                Polyline routePolyline = route.RouteGeometry;
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Blue, 3.0);
                routeGraphic = new Graphic(routePolyline, routeSymbol);
                _routeGraphicsOverlay.Graphics.Add(routeGraphic);
                //await MyMapView.SetViewpointGeometryAsync(routeGraphic.Geometry, 50);

                IReadOnlyList<DirectionManeuver> directionsList = route.DirectionManeuvers;
                DirectionsListBox.ItemsSource = directionsList;

                routeLine.Width = routeBox.Width;
                routeLine.Visibility = Visibility.Visible;
            }
            catch
            {
                MessageBox.Show("出现错误");
            }
        }

        private void ClearRoute_Click(object sender, RoutedEventArgs e)
        {
            startTextBox.Text = "请输入起点";
            endTextBox.Text = "请输入终点";
            viaTextBox.Text = "非必填，可多点";
            routeLine.Visibility = Visibility.Hidden;
            if (_routeGraphicsOverlay.Graphics.Count > 0) _routeGraphicsOverlay.Graphics.Clear();
        }

        private void CloseRoute_Click(object sender, RoutedEventArgs e)
        {
            startTextBox.Text = "请输入起点";
            endTextBox.Text = "请输入终点";
            viaTextBox.Text = "非必填，可多点";
            if (_routeGraphicsOverlay.Graphics.Count > 0) _routeGraphicsOverlay.Graphics.Clear();
            routeBox.Visibility = Visibility.Hidden;
            routeLine.Visibility = Visibility.Hidden;
        }


        //为 MapView 的 MouseLeftButtonDown 事件处理添加代码
        private async void MyMapView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //获取鼠标左键点击的位置坐标
            IInputElement mv = (IInputElement)sender;
            location = MyMapView.ScreenToLocation(e.GetPosition(mv));
            //Console.WriteLine($"当前点击的点：{location.X},{location.Y}");
            if (m_CurOper == CURRENTOPERATION.ZoomEnv)
            {
                //两点构建矩形框。将点加入点集。if判断点集数是否小于2，是则返回。
                linePoints.Add(location);
                if (linePoints.Count < 2) return;
                //两点构建矩形，加入绘图层，显示在地图界面。
                Envelope selEnv = new Envelope(linePoints[0], linePoints[1]);
                Graphic EnvGraphic = new Graphic(selEnv, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 255, 250, 0), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1.0)));//√
                _routeGraphicsOverlay.Graphics.Add(EnvGraphic);
                await MyMapView.SetViewpointGeometryAsync(EnvGraphic.Geometry, 50);
                _routeGraphicsOverlay.Graphics.Remove(EnvGraphic);
                linePoints.Clear();
                m_CurOper = CURRENTOPERATION.None;

            }
            else if (m_CurOper == CURRENTOPERATION.StartTextBox)// 路径查询
            {
                fromPoint = location;
                if (startGraphic != null) _routeGraphicsOverlay.Graphics.Remove(startGraphic);

                routeLine.Visibility = Visibility.Hidden;
                if (routeGraphic != null) _routeGraphicsOverlay.Graphics.Remove(routeGraphic);

                startTextBox.Text = $"{Math.Round(location.X, 3)},{Math.Round(location.Y, 3)}";
                // create a new PictureMarkerSymbol with an image file stored locally
                var picPath = @"..\..\Image\Icon\car.png";
                PictureMarkerSymbol startSymbol;
                using (System.IO.FileStream picStream = new System.IO.FileStream(picPath,
                System.IO.FileMode.Open))
                {
                    // pass the image file stream to the symbol constructor
                    startSymbol = await PictureMarkerSymbol.CreateAsync(picStream);
                }
                startSymbol.Width = 30;
                startSymbol.Height = 30;
                startSymbol.OffsetY = startSymbol.Height / 2;
                startGraphic = new Graphic(location, startSymbol);
                _routeGraphicsOverlay.Graphics.Add(startGraphic);
                m_CurOper = CURRENTOPERATION.None;

            }
            else if (m_CurOper == CURRENTOPERATION.EndTextBox)
            {
                toPoint = location;
                if (startGraphic != null) _routeGraphicsOverlay.Graphics.Remove(endGraphic);

                routeLine.Visibility = Visibility.Hidden;
                if (routeGraphic != null) _routeGraphicsOverlay.Graphics.Remove(routeGraphic);

                endTextBox.Text = $"{Math.Round(location.X, 3)},{Math.Round(location.Y, 3)}";

                // create a new PictureMarkerSymbol with an image file stored locally
                var picPath = @"..\..\Image\Icon\to.png";
                PictureMarkerSymbol endSymbol;
                using (System.IO.FileStream picStream = new System.IO.FileStream(picPath,
                System.IO.FileMode.Open))
                {
                    // pass the image file stream to the symbol constructor
                    endSymbol = await PictureMarkerSymbol.CreateAsync(picStream);
                }
                endSymbol.Width = 30;
                endSymbol.Height = 30;
                endSymbol.OffsetY = endSymbol.Height / 2;
                endGraphic = new Graphic(location, endSymbol);
                _routeGraphicsOverlay.Graphics.Add(endGraphic);
                m_CurOper = CURRENTOPERATION.None;
            }
            else if (m_CurOper == CURRENTOPERATION.ViaTextBox)
            {
                routeLine.Visibility = Visibility.Hidden;
                if (routeGraphic != null) _routeGraphicsOverlay.Graphics.Remove(routeGraphic);
                if (viaTextBox.Text.ToString().IndexOf("可")==-1)
                {
                    viaTextBox.Text = viaTextBox.Text + $"{Math.Round(location.X, 3)},{Math.Round(location.Y, 3)};";
                }
                else
                {
                    viaTextBox.Text = $"{Math.Round(location.X, 3)},{Math.Round(location.Y, 3)};";
                }
                viaStops.Add(new Stop(location));
                // create a new PictureMarkerSymbol with an image file stored locally
                var picPath = @"..\..\Image\Icon\via.png";
                PictureMarkerSymbol endSymbol;
                using (System.IO.FileStream picStream = new System.IO.FileStream(picPath,
                System.IO.FileMode.Open))
                {
                    // pass the image file stream to the symbol constructor
                    endSymbol = await PictureMarkerSymbol.CreateAsync(picStream);
                }
                endSymbol.Width = 30;
                endSymbol.Height = 30;
                endSymbol.OffsetY = endSymbol.Height / 2;
                _routeGraphicsOverlay.Graphics.Add(new Graphic(location, endSymbol));
                return;
            }
            

        }

        // 打开赏花路径窗口
        private void ViewFlower_Click(object sender, RoutedEventArgs e)
        {
            if (networkPath == null)
            {
                MessageBox.Show("请先设置网络数据集路径");
                return;
            }
            ViewFlowersRouteWindow vfrw = new ViewFlowersRouteWindow(MyMapView, networkPath, networkName);
            vfrw.Show();
            vfrw.Activate();
        }

        // 加载Shp文件
        private void AddShp_click(object sender, RoutedEventArgs e)
        {
            OpenShp();
        }

        private async void OpenShp()
        {
            //新建一个文件对话框
            OpenFileDialog shp = new OpenFileDialog();
            //设置对话框可以多选
            shp.Multiselect = true;
            //设置可以在对话框中显示的文件筛选器
            shp.Filter = "Shapefile文件(*.shp)|*.shp";
            //设置显示在对话框标题栏中的名称
            shp.Title = "打开Shapefile文件";
            //if判断对话框的返回值
            if (shp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //for循环获取对话框中所有选定的文件的文件绝对路径，并依次打开文件
                for (int i = 0; i < shp.FileNames.Length; i++)
                {
                    string fPath = shp.FileNames.GetValue(i).ToString();
                    ShapefileFeatureTable myShapefile = await ShapefileFeatureTable.OpenAsync(fPath);
                    FeatureLayer newFeaturelayer = new FeatureLayer(myShapefile);
                    MyMapView.Map.OperationalLayers.Add(newFeaturelayer);
                    await MyMapView.SetViewpointGeometryAsync(newFeaturelayer.FullExtent);
                }
            }
            //加载至图层管理列表
            AddLayerNameToList();
        }
        
        // 加载Geo文件
        private void AddGeo_click(object sender, RoutedEventArgs e)
        {
            OpenGeo();
        }
        private async void OpenGeo()
        {
            //新建一个文件对话框
            OpenFileDialog geo = new OpenFileDialog();
            //设置可以在对话框中显示的文件筛选器
            geo.Filter = "文件(*.geodatabase)|*.geodatabase";
            //设置显示在对话框标题栏中的名称
            geo.Title = "打开Geodatabase文件";
            //if判断对话框的返回值是否是OK
            if (geo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获取Geodatabase文件路径，并打开
                string _slocalGeodatabasePath = geo.FileName;
                Geodatabase _localGeodatabase = await Geodatabase.OpenAsync(_slocalGeodatabasePath);
                //获取Geodatabase文件中包含的图层数量
                int beginCount = _localGeodatabase.GeodatabaseFeatureTables.Count - 1;
                //for循环获取Geodatabase里包含的图层并打开加载至地图业务层
                FeatureLayer _featureLayerGeo=null;
                for (int i = beginCount; i >= 0; i--)
                {
                    GeodatabaseFeatureTable table = _localGeodatabase.GeodatabaseFeatureTables[i];
                    await table.LoadAsync();
                    FeatureLayer layer = new FeatureLayer(table)
                    {
                        Name = table.TableName
                    };
                    MyMapView.Map.OperationalLayers.Add(layer);
                    _featureLayerGeo = layer;
                }
                //缩放至全图显示
                if(_featureLayerGeo!=null)
                await MyMapView.SetViewpointGeometryAsync(_featureLayerGeo.FullExtent, 50);
            }
            //加载至图层管理列表
            AddLayerNameToList();
        }

        // 加载网络数据集文件
        private void AddNetworkGeo_click(object sender, RoutedEventArgs e)
        {
            OpenNetGeo();
        }
        private void OpenNetGeo()
        {
            SetNetworkPathWindow snpw = new SetNetworkPathWindow(this);
            snpw.ShowDialog();
        }

        // 退出程序
        private void Quit_click(object sender, RoutedEventArgs e)
        {
            //新建消息框，让用户做判断，如果返回值为True,则退出程序，反之不退。
            if (System.Windows.MessageBox.Show("确定退出？", "退出程序", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();
            }
        }


        // 2、视图显示功能：放大、缩小、漫游等。

        // 放大
        private async void zoomIn_Click(object sender, RoutedEventArgs e)
        {
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;

            //获取当前地图视图的位置
            Viewpoint pVP = MyMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale);
            //获取当前视图目标几何位置
            MapPoint pPoint = (MapPoint)pVP.TargetGeometry;
            //新建一个视图范围，输入参数一为前面获取的视图几何位置点，参数二为之前视图比例尺/2
            Viewpoint pNewVP = new Viewpoint(pPoint, pVP.TargetScale / 2.0);
            //设置地图视图为刚刚新建的视图
            await MyMapView.SetViewpointAsync(pNewVP);
        }
        // 缩小
        private async void zoomOut_Click(object sender, RoutedEventArgs e)
        {
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            //获取当前地图视图的位置
            Viewpoint pVP = MyMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale);
            //获取当前视图目标几何位置
            MapPoint pPoint = (MapPoint)pVP.TargetGeometry;
            //新建一个视图范围，输入参数一为前面获取的视图几何位置点，参数二为之前视图比例尺×2
            Viewpoint pNewVP = new Viewpoint(pPoint, pVP.TargetScale * 2.0);
            //设置地图视图为刚刚新建的视图
            await MyMapView.SetViewpointAsync(pNewVP);
        }
        // 旋转
        private async void zoomRotate_Click(object sender, RoutedEventArgs e)
        {
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            //使用SetViewpointRotationAsync()设置地图旋转角度
            await MyMapView.SetViewpointRotationAsync(MyMapView.MapRotation + 90);
        }
        // 全图
        private async void zoomAll_Click(object sender, RoutedEventArgs e)
        {
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            //首先将地图旋转回正
            await MyMapView.SetViewpointRotationAsync(0);

            //Console.WriteLine(MyMapView.Map.OperationalLayers.Count());
            int count = MyMapView.Map.OperationalLayers.Count();
            List<Layer> pListFeatures = MyMapView.Map.OperationalLayers.ToList();
            List<Geometry> grometries = new List<Geometry>();
            GraphicsOverlay _OverLay = new GraphicsOverlay();
            Geometry k;
            for (int i = 0; i < count; i++)
            {
                //Console.WriteLine(pListFeatures[i].SpatialReference);
                if (!pListFeatures[i].SpatialReference.IsEqual(MyMapView.SpatialReference))
                {
                    k = GeometryEngine.Project(pListFeatures[i].FullExtent, MyMapView.SpatialReference);
                }
                else
                {
                    k = pListFeatures[i].FullExtent;
                }
                grometries.Add(k);
                Graphic EnvGraphic = new Graphic(k);
                _OverLay.Graphics.Add(EnvGraphic);
            }
            MyMapView.GraphicsOverlays.Add(_OverLay);
            await MyMapView.SetViewpointGeometryAsync(_OverLay.Extent);
            MyMapView.GraphicsOverlays.Remove(_OverLay);
        }

        // 漫游
        private void zoomRoam_Click(object sender, RoutedEventArgs e)
        {
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            //if判断m_CurOper是否已经是Roam(漫游)，是则改为None(暂停),否则改为Roam(漫游)
            if (m_CurOper != CURRENTOPERATION.Roam)
            {
                m_CurOper = CURRENTOPERATION.Roam;
            }
            else
            {
                m_CurOper = CURRENTOPERATION.None;
            }
        }
        
        //矩形框选视图范围
        private void zoomEnvlope_Click(object sender, RoutedEventArgs e)
        {
            m_CurOper = CURRENTOPERATION.ZoomEnv;
        }

        // 识别
        private void identify_Click(object sender, RoutedEventArgs e)
        {
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            //if判断当前业务层图层个数是否大于0，是则进入语句
            if (MyMapView.Map.OperationalLayers.Count > 0)
            {
                if (iqw != null)
                {
                    iqwIsExist = iqw.isLoad;
                }
                if (!iqwIsExist)
                {
                    iqw = null;
                    iqw = new IdentifyQueryWindow(MyMapView, identifyPoint, FeatureQuery);
                    iqw.Show();
                }
                else
                {
                    iqw.MPoint = identifyPoint;
                    iqw.Activate();
                }

            }
        }
        private async void MyMapView_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            // 状态栏
            MapPoint location = MyMapView.ScreenToLocation(e.GetPosition(MyMapView));
            if (location != null)
            {
                LocationStatusBar.Content = $"{Math.Round(location.X, 3)} {Math.Round(location.Y, 3)} 米";
            }
            //if判断是否为Roam(漫游),是则进入语句
            if (m_CurOper == CURRENTOPERATION.Roam)
            {
                //获取当前鼠标屏幕位置并转为地图坐标
                MapPoint Location = MyMapView.ScreenToLocation(e.GetPosition(MyMapView));
                //设置当前鼠标位置为视图更新，即实现地图漫游
                await MyMapView.SetViewpointCenterAsync(Location);
            }

        }


        // 3、图层的管理：图层的可见、图层的移动、图层的删除等。

        // 监视图层管理的鼠标事件
        private void LayerListBox_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (rightClick.IsVisible) rightClick.Visibility = Visibility.Hidden;
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            //在LayerListBox中监视鼠标事件
            //if判断是否发生鼠标左键按压事件
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                //判断鼠标左击位置是否为图层控件元素，是则获取
                var pos = e.GetPosition(LayerListBox);
                if (pos.X < 20)
                    return;
                System.Windows.Media.HitTestResult result = System.Windows.Media.VisualTreeHelper.HitTest(LayerListBox, pos);
                if (result == null)
                    return;
                var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
                if (listBoxItem == null)
                {
                    return;
                }
                //创建可拖动对象，并启动拖动
                System.Windows.DataObject dataObj = new System.Windows.DataObject(listBoxItem.Content as CheckBox);
                DragDrop.DoDragDrop(LayerListBox, dataObj, System.Windows.DragDropEffects.Move);
            }
            //判断鼠标是否发生鼠标右键按压事件
            else if (e.RightButton == MouseButtonState.Pressed)
            {
                //判断鼠标右击位置是否为图层控件元素，是则获取
                var pos = e.GetPosition(LayerListBox);
                //Console.WriteLine($"{pos.X},{pos.Y}");
                double y = pos.Y;
                //if (y > 320) y = 320;
                rightClick.Margin = new Thickness(pos.X, y+30, 0, 0);
                if (pos.X < 20)
                    return;
                System.Windows.Media.HitTestResult result = System.Windows.Media.VisualTreeHelper.HitTest(LayerListBox, pos);
                if (result == null)
                    return;
                var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
                if (listBoxItem == null)
                {
                    rightClick.Visibility = Visibility.Hidden;
                    return;
                }
                //将右击的图层赋值给全局变量rightButton_name，方便后面对该图层的操作
                rightButton_name = listBoxItem.Content as System.Windows.Controls.CheckBox;
                //鼠标右击图层界面可见
                rightClick.Visibility = Visibility.Visible;
            }
        }
        // 添加图层名称到图层列表
        public void AddLayerNameToList()
        {
            //清空图层列表
            LayerListBox.Items.Clear();
            LayerListBox.AllowDrop = true;
            LayerCollection pLayers = MyMapView.Map.OperationalLayers;
            //if判断地图业务层是否含有图层
            if (pLayers.Count <= 0)
                return;
            //for循环遍历地图业务层的所有图层，并创建控件CheakBox，设置相关属性，将每个图层的图层名赋值给CheckBox控件,并添加为LayerListBox控件的子项
            for (int i = pLayers.Count - 1; i >= 0; i--)
            {

                System.Windows.Controls.CheckBox cb = new System.Windows.Controls.CheckBox()
                {
                    Margin = new Thickness()
                    {
                        Left = 0,
                        Top = 5,
                        Right = 0,
                        Bottom = 5
                    },
                };
                cb.Content = pLayers[i].Name;
                cb.ToolTip = cb.Content;
                cb.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue);
                cb.FontSize = 12;
                try
                {
                    cb.Name = pLayers[i].Name;
                }
                catch
                {
                    cb.Name = "nb";
                }
                cb.DataContext = pLayers[i];
                cb.IsChecked = true;
                cb.Focusable = false;
                cb.Checked += new RoutedEventHandler(Checked_Layers_CheckBox);
                cb.Unchecked += new RoutedEventHandler(UnChecked_Layers_CheckBox);
                LayerListBox.Items.Add(cb);
                LayerListBoxWrap.Visibility = Visibility.Visible;
            }
            //将每次最后添加的一个图层赋值给全局变量P_featureLayer，即当前操作图层
            P_featureLayer = MyMapView.Map.OperationalLayers[MyMapView.Map.OperationalLayers.Count - 1] as FeatureLayer;
        }
        internal static class Utils
        {
            //根据子元素查找父元素
            public static T FindVisualParent<T>(DependencyObject obj) where T : class
            {
                while (obj != null)
                {
                    if (obj is T)
                        return obj as T;
                    obj = System.Windows.Media.VisualTreeHelper.GetParent(obj);
                }
                return null;
            }
        }

        //设置所选择的图层可见
        private void Checked_Layers_CheckBox(object sender, RoutedEventArgs e)
        {
            //获取当前勾选的图层在地图业务层的索引值，然后根据索引值将图层设为可见
            System.Windows.Controls.CheckBox cb = sender as System.Windows.Controls.CheckBox;
            Layer la = cb.DataContext as Layer;
            la.IsVisible = true;
            //int index = GetLayerIndex(cb.Name);
            //MyMapView.Map.OperationalLayers[index].IsVisible = true;
        }
        //设置所选择的图层不可见
        private void UnChecked_Layers_CheckBox(object sender, RoutedEventArgs e)
        {
            //获取当前取消勾选的图层在地图业务层的索引值，然后根据索引值将图层设为不可见
            System.Windows.Controls.CheckBox cb = sender as System.Windows.Controls.CheckBox;
            Layer la = cb.DataContext as Layer;
            la.IsVisible = false;
            //int index = GetLayerIndex(cb.Name);
            //MyMapView.Map.OperationalLayers[index].IsVisible = false;
        }

        //地图中图层顺序移动
        private void MoveLayer(Layer sourceLayer, Layer targetLayer)
        {
            //根据参数图层，对拖动图层在地图业务层的位置进行移动
            LayerCollection pLayers = MyMapView.Map.OperationalLayers;
            pLayers.Remove(sourceLayer);
            int targerIndex = pLayers.IndexOf(targetLayer);
            pLayers.Insert(targerIndex + 1, sourceLayer);
        }
        //移动图层
        private void LayerListBox_Drop(object sender, System.Windows.DragEventArgs e)
        {
            var pos = e.GetPosition(LayerListBox);
            var result = System.Windows.Media.VisualTreeHelper.HitTest(LayerListBox, pos);
            if (result == null)
            {
                return;
            }
            //查找拖动图层，即源图层
            var sourcePerson = e.Data.GetData(typeof(System.Windows.Controls.CheckBox)) as System.Windows.Controls.CheckBox;
            if (sourcePerson == null)
            {
                return;
            }
            //查找鼠标松开时，所在位置的图层，即目标图层
            var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
            if (listBoxItem == null)
            {
                return;
            }
            var targetPerson = listBoxItem.Content as System.Windows.Controls.CheckBox;
            if (ReferenceEquals(targetPerson, sourcePerson))
            {
                return;
            }
            //图层管理器的图层名称控件的移动
            LayerListBox.Items.Remove(sourcePerson);
            LayerListBox.Items.Insert(LayerListBox.Items.IndexOf(targetPerson), sourcePerson);
            //地图业务层中图层顺序移动
            MoveLayer(sourcePerson.DataContext as Layer, targetPerson.DataContext as Layer);
        }

        // 图层置顶
        private void LayerToTop_Click(object sender, RoutedEventArgs e)
        {
            rightClick.Visibility = Visibility.Hidden;

            //图层管理器的图层名称控件的移动
            LayerListBox.Items.Remove(rightButton_name);
            LayerListBox.Items.Insert(0, rightButton_name);

            //根据参数图层，对拖动图层在地图业务层的位置进行移动
            LayerCollection pLayers = MyMapView.Map.OperationalLayers;
            pLayers.Remove(rightButton_name.DataContext as FeatureLayer);
            pLayers.Add(rightButton_name.DataContext as FeatureLayer);
        }

        //打开属性表
        private void AttributeTable_Click(object sender, RoutedEventArgs e)
        {
            List<FeatureLayer> featureLayerCollections = new List<FeatureLayer>();//地图所有有属性表的图层
            rightClick.Visibility = Visibility.Hidden;
            if (typeof(FeatureCollectionLayer) == rightButton_name.DataContext.GetType())
            {
                MessageBox.Show("待完善中...");
                return;
            }
            FeatureLayer now = rightButton_name.DataContext as FeatureLayer;
            AttributeTableWindow attr = new AttributeTableWindow(now,MyMapView, FeatureQuery);
            attr.Show();
            attr.Activate();
        }

        //删除当前选择图层
        private void DeleteLayer_Click(object sender, RoutedEventArgs e)
        {
            //通过全局变量rightButton_name，获取当前的控件名称对应的图层。然后在图层管理器移除，在地图业务层中删除
            rightClick.Visibility = Visibility.Hidden;
            LayerCollection pLayers = MyMapView.Map.OperationalLayers;
            Layer sourcLayer = rightButton_name.DataContext as Layer;
            pLayers.Remove(sourcLayer);
            LayerListBox.Items.Remove(rightButton_name);
            if (MyMapView.Map.OperationalLayers.Count == 0)
            {
                P_featureLayer = null;
            }

        }

        //缩放至当前图层
        private async void Scale_Zoom(object sender, RoutedEventArgs e)
        {
            //通过全局变量rightButton_name，获取当前的控件名称对应的图层，SetViewpointGeometryAsync()进行视图图层缩放
            rightClick.Visibility = Visibility.Hidden;
            LayerCollection pLayers = MyMapView.Map.OperationalLayers;
            Layer sourcLayer = rightButton_name.DataContext as Layer;
            await MyMapView.SetViewpointGeometryAsync(sourcLayer.FullExtent, 50);

        }

        //设置当前图层操作
        private void OperationLayer_Click(object sender, RoutedEventArgs e)
        {
            //通过全局变量rightButton_name，获取当前的控件名称对应的图层，赋值给全局变量P_featureLayer(当前操作图层)
            rightClick.Visibility = Visibility.Hidden;
            P_featureLayer =rightButton_name.DataContext as FeatureLayer;
        }

        // 5、符号设置：点、线、面的符号界面设计与实现。
        //展示窗体
        private void Options_Click(object sender, RoutedEventArgs e)
        {
            //新建OptionsWindows窗口，并赋值点线面符号样式，展示窗口
            OptionsWindows sForm = new OptionsWindows(P_featureLayer);
            sForm.ShowDialog();
        }

        // 6、查询：实现由属性至图形的查询，以及由图形至属性的查询。提供查询通用界面，并将查询的结果显示出来，考虑提供通用设计界面。
        // 点击查询
        private void PointSelectFeat_Click(object sender, RoutedEventArgs e)
        {
            //将m_CurOper设为IdentifyQuery
            m_CurOper = CURRENTOPERATION.IdentifyQuery;
        }

        // 按属性查询
        private void ByAttribute_Click(object sender, RoutedEventArgs e)
        {
            //创建查询窗体QueryWindow对象
            QueryWindow qw = new QueryWindow(FeatureQuery);
            //为窗体对象的表集合对象添加表集合
            List<FeatureLayer> myLayers = new List<FeatureLayer>();
            for (int i = MyMapView.Map.OperationalLayers.Count-1; i >=0 ; i--)
            {
                FeatureLayer pFL = MyMapView.Map.OperationalLayers[i] as FeatureLayer;
                if (pFL != null)
                {
                    myLayers.Add(pFL);
                }
            }
            qw.Tables.AddRange(myLayers);
            //以对话框方式显示该子窗体
            bool r = (bool)qw.ShowDialog();
        }

        // 清除所选要素
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            //for循环遍历每个图层ClearSelection()方法
            int cou = MyMapView.Map.OperationalLayers.Count;
            for (int i = 0; i < cou; i++)
            {
                FeatureLayer pFL = MyMapView.Map.OperationalLayers[i] as FeatureLayer;
                pFL.ClearSelection();
            }
            if (FeatureQuery!=null && FeatureQuery.Count > 0) FeatureQuery.Clear();
        }


        // 7、专题图表达：实现多种专题图的表达方式，考虑提供通用设计界面。
        private void UniqueValueRenderer_Click(object sender, RoutedEventArgs e)
        {
            UniqueValueRenderWindow uvrw = new UniqueValueRenderWindow(this);
            uvrw.ShowDialog();
        }

        // 分级着色
        private void ClassBreaksRender_Click(object sender, RoutedEventArgs e)
        {
            //创建分级着色窗口ClassBreaksRenderWindow，并进行相关属性传递
            ClassBreaksRenderWindow cbr = new ClassBreaksRenderWindow(this);
            cbr.Show();
            cbr.Activate();
        }

        // 符号化作色（鼠标右键）
        private void Symbol_Click(object sender, RoutedEventArgs e)
        {
            rightClick.Visibility = Visibility.Hidden;
            //获取鼠标右击图层管理器列表的图层，赋值给全局变量P_featureLayer，即当前操作图层
            if (typeof(FeatureCollectionLayer) == rightButton_name.DataContext.GetType())
            {
                MessageBox.Show("新增的图层着色没时间弄了...");
                return;
            }
            P_featureLayer = rightButton_name.DataContext as FeatureLayer;
            try
            {
                Symbol_SimpleRender(P_featureLayer);
            }
            catch
            {
                MessageBox.Show("出现一点小问题，待完善中...");
            }
        }
        private void Symbol_SimpleRender(FeatureLayer pLayer)
        {
            //创建点线面符号化设计窗口
            OptionsWindows sForm = new OptionsWindows(pLayer);
            sForm.ShowDialog();
        }


        // 8、空间分析：几何图形的缓冲分析。

        // 缓冲区分析
        private void Buffer_analysis_Click(object sender, RoutedEventArgs e)
        {
            BufferWindow bf = new BufferWindow(this);
            bf.Show();
            bf.Activate();
        }
        // 生成缓冲几何
        private void BufferGeometry_analysis_Click(object sender, RoutedEventArgs e)
        {
            BufferGeometryWindow bgw = new BufferGeometryWindow(MyMapView, FeatureQuery);
            bgw.Show();
            bgw.Activate();
        }
        // 清除缓冲几何
        private void ClearGeometry_Click(object sender, RoutedEventArgs e)
        {
            if(_routeGraphicsOverlay.Graphics.Count>0)
            _routeGraphicsOverlay.Graphics.RemoveAt(_routeGraphicsOverlay.Graphics.Count-1);
        }
        //为 MapView 的 MouseRightButtonDown 事件处理添加代码
        private void MyMapView_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 地图范围右击菜单栏
            if (rightClick.IsVisible) rightClick.Visibility = Visibility.Hidden;
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
            var pos = e.GetPosition(MapGrid);

            identifyPoint = MyMapView.ScreenToLocation(e.GetPosition(MyMapView));
            //Console.WriteLine($"{pos.X},{pos.Y}");
            double x = pos.X;
            double y = pos.Y;
            //if (y > 350) y = 350;
            //if (x > 770) x = 770;
            mapRightClick.Margin = new Thickness(x, y, 0, 0);
            mapRightClick.Visibility = Visibility.Visible;
        }

        private void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e)
        {
            //点击查询
            if (m_CurOper == CURRENTOPERATION.IdentifyQuery)
            {
                //if判断当前业务层图层个数是否大于0，是则进入语句
                if (MyMapView.Map.OperationalLayers.Count > 0)
                {
                    if (iqw != null)
                    {
                        iqwIsExist = iqw.isLoad;
                    }
                    if (!iqwIsExist)
                    {
                        iqw = null;
                        iqw = new IdentifyQueryWindow(MyMapView, e.Location, FeatureQuery);
                        iqw.Show();
                    }
                    else
                    {
                        iqw.MPoint = e.Location;
                        iqw.Activate();
                    }

                }
                m_CurOper = CURRENTOPERATION.None;
            }
        }

        // toolbar的子控件
        private void ToolBarButton1_Click(object sender, RoutedEventArgs e)
        {
            OpenNetGeo();
        }

        private void ToolBarButton2_Click(object sender, RoutedEventArgs e)
        {
            OpenGeo();
        }

        private void ToolBarButton3_Click(object sender, RoutedEventArgs e)
        {
            if (MeasureToolbar.IsVisible)
            {
                MeasureToolbar.Visibility = Visibility.Hidden;
            }
            else
            {
                MeasureToolbar.Visibility = Visibility.Visible;
            }

        }

        private void ToolBarButton4_Click(object sender, RoutedEventArgs e)
        {
            if (System.Windows.MessageBox.Show("确定退出？", "退出程序", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();
            }
        }

        private void ToolBarButton5_Click(object sender, RoutedEventArgs e)
        {
            if (P_featureLayer == null)
            {
                try
                {
                    P_featureLayer = MyMapView.Map.OperationalLayers[MyMapView.Map.OperationalLayers.Count - 1] as FeatureLayer;
                }
                catch
                {
                    MessageBoxResult tip = System.Windows.MessageBox.Show("目前图层为空，请加载图层后重试！", "Tip", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "shapefile文件(*.shp)|*.shp";
            sf.FileName = P_featureLayer.Name;
            sf.AddExtension = true;
            sf.RestoreDirectory = true;
            // Show save file dialog box
            DialogResult result = sf.ShowDialog();
            //点了保存按钮进入
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                //获得文件路径
                string localFilePath = sf.FileName.ToString();

                //获取文件名，不带路径
                //fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);

                //获取文件路径，不带文件名
                //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));

                //给文件名前加上时间
                //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;

                //在文件名里加字符
                //saveFileDialog.FileName.Insert(1,"dameng");
                //为用户使用 SaveFileDialog 选定的文件名创建读/写文件流。
                //System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog.OpenFile();//输出文件

                //fs可以用于其他要写入的操作
                if (!string.IsNullOrEmpty(localFilePath))
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(localFilePath, true, Encoding.UTF8);
                    sw.Write(P_featureLayer);
                    sw.Close();
                    System.Windows.Forms.MessageBox.Show("保存成功！", "提示");
                }
            }

        }


        private void MyGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (rightClick.IsVisible) rightClick.Visibility = Visibility.Hidden;
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
        }

        // 男女生比例专题图
        private void PieRender_Click(object sender, RoutedEventArgs e)
        {
            if (_pieGraphicsOverlay.Graphics.Count > 0)
            {
                _pieGraphicsOverlay.IsVisible = !_pieGraphicsOverlay.IsVisible;
                return;
            }
             QueryAmount();
        }

        public static byte[] BitmapToByte(System.Drawing.Bitmap bitmap)
        {
            // 1.先将BitMap转成内存流
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);  // 必须是PNG
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            // 2.再将内存流转成byte[]并返回
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Dispose();
            return bytes;
        }

        // 生成图形
        private async void QueryAmount()
        {
            FeatureLayer featureLayer = null;
            LayerCollection featureCollectionLayer = MyMapView.Map.OperationalLayers;
            for (var i = featureCollectionLayer.Count - 1; i >= 0; i--)
            {
                if (featureCollectionLayer[i].Name == "StudentDormitory")
                {
                    featureLayer = featureCollectionLayer[i] as FeatureLayer;
                }
            }
            if (featureLayer == null)
            {
                MessageBox.Show("没有找到StudentDormitory图层");
                return;
            }
            List<string> dormitoryArea = new List<string>();
            
            FeatureQueryResult result = await featureLayer.FeatureTable.QueryFeaturesAsync(new QueryParameters());//构建查询参数对象在表对象上进行查询
            if (result == null) return;
            foreach (Feature ft in result)//遍历查询结果
            {
                string strValue = null;
                try
                {
                    strValue = ft.GetAttributeValue("宿舍区").ToString();//取得当前字段值
                }
                catch
                {
                    return;
                }
                if (!dormitoryArea.Contains(strValue))//检查该值是否已存在
                {
                    dormitoryArea.Add(strValue);//加入字段值列表框
                }
            }
            for(int i = dormitoryArea.Count-1; i >= 0; i--)
            {
                string name = dormitoryArea[i];
                QueryParameters qParams = new QueryParameters();//创建查询参数对象
                                                                // 求女生总数
                qParams.WhereClause = $"宿舍区 = '{name}' AND 宿舍类型 = '女'";//获取文本框中的字符串作为查询参数对象的where子句
                FeatureQueryResult result1 = await featureLayer.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                float peopleGirl = 0;
                foreach (Feature f in result1)
                {
                    peopleGirl += Convert.ToInt32(f.GetAttributeValue("已住人数"));//取得当前字段值
                }
                // 求男生总数
                qParams.WhereClause = $"宿舍区 = '{name}' AND 宿舍类型 = '男'";//获取文本框中的字符串作为查询参数对象的where子句
                FeatureQueryResult result2 = await featureLayer.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                float peopleBoy = 0;
                foreach (Feature f in result2)
                {
                    peopleBoy += Convert.ToInt32(f.GetAttributeValue("已住人数"));//取得当前字段值
                }
                // 求宿舍区几何中心
                qParams.WhereClause = $"宿舍区 = '{name}'";//获取文本框中的字符串作为查询参数对象的where子句
                FeatureQueryResult result3 = await featureLayer.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                List<Geometry> geometries = new List<Geometry>();
                foreach (Feature f in result3)
                {
                    geometries.Add(f.Geometry.Extent);
                }
                Geometry geometry = GeometryEngine.Union(geometries);
                MapPoint center = new MapPoint((geometry.Extent.XMax + geometry.Extent.XMin) / 2, (geometry.Extent.YMin + geometry.Extent.YMax) / 2, geometry.SpatialReference);
                center = GeometryEngine.Project(center, new SpatialReference(3857)) as MapPoint;
                float start = peopleBoy / (peopleBoy + peopleGirl) * 360;
                //Console.WriteLine($"宿舍区：{name}，男：{peopleBoy}，女：{peopleGirl}，分割值：{start}，中心点：{center.X},{center.Y}");

                //生成图形
                Bitmap bitmap = new Bitmap(400, 500);
                bitmap.MakeTransparent();
                Graphics graphics = Graphics.FromImage(bitmap);
                graphics.SmoothingMode = SmoothingMode.AntiAlias;

                // 画字
                Brush brush = new SolidBrush(Color.Black);
                Font font = new Font("楷体", 40, System.Drawing.FontStyle.Bold); //第一个是字体，第二个大小，第三个是样式
                graphics.DrawString(name, font, brush, 80, 400);
                // 画扇形
                Pen pen = new Pen(Color.Red);
                Rectangle rct = new Rectangle(0, 0, 400, 400);
                Brush brush1 = new SolidBrush(Color.SkyBlue);
                graphics.DrawPie(pen, rct, 0, start);//绘制扇形
                graphics.FillPie(brush1, rct, 0, start);//填充扇形;

                Brush brush2 = new SolidBrush(Color.LightPink);
                graphics.DrawPie(pen, rct, start, 360 - start);//绘制扇形
                graphics.FillPie(brush2, rct, start, 360 - start);//填充扇形;
                pen.Dispose();
                graphics.Dispose();
                // 转换位点符号渲染
                RuntimeImage runtimeImage = new RuntimeImage(BitmapToByte(bitmap));
                PictureMarkerSymbol pSymbol = new PictureMarkerSymbol(runtimeImage);
                // 4:5
                pSymbol.Width = 64;
                pSymbol.Height = 80;
                Graphic pGraphic = new Graphic(center, pSymbol);
                _pieGraphicsOverlay.Graphics.Add(pGraphic);
            }
        }

        private void locationQuery_Click(object sender, RoutedEventArgs e)
        {
            LocationQueryWindow lqw = new LocationQueryWindow(MyMapView,this);
            lqw.Activate();
            lqw.Show();
        }

        private void siteSelection_Click(object sender, RoutedEventArgs e)
        {
            SiteSelectionWindow ssw = new SiteSelectionWindow(MyMapView, _siteGraphicsOverlay);
            ssw.ShowDialog();
        }

        private void clearSiteSelection_Click(object sender, RoutedEventArgs e)
        {
            if (_siteGraphicsOverlay.Graphics.Count > 0) _siteGraphicsOverlay.Graphics.Clear();
        }

        // 柱状图
        private void HistogramRender_Click(object sender, RoutedEventArgs e)
        {
            HistogramWindow hw = new HistogramWindow(MyMapView.Map.OperationalLayers);

            hw.Activate();
            hw.Show();
        }

        // 图层显示
        private void LayerShow_Checked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            foreach (CheckBox cb in LayerListBox.Items)
            {
                cb.IsChecked = true;
            }
        }
        // 图层隐藏
        private void LayerShow_Unchecked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            foreach (CheckBox cb in LayerListBox.Items)
            {
                cb.IsChecked = false;
            }
        }
        //列表显示
        private void ListShow_Checked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            LayerListBoxWrap.Visibility = Visibility.Visible;
            MapArea.Margin = new Thickness()
            {
                Left = 180,
                Top = 0,
                Right = 0,
                Bottom = 20
            };
        }
        //列表隐藏
        private void ListShow_Unchecked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            LayerListBoxWrap.Visibility = Visibility.Hidden;
            MapArea.Margin = new Thickness()
            {
                Left = 0,
                Top = 0,
                Right = 0,
                Bottom = 20
            };
        }

        private void NoMap_Checked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            MyMapView.Map.Basemap = null;
        }

        private void VectorMap_Checked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            MyMapView.Map.Basemap = Basemap.CreateOpenStreetMap();
            //MyMapView.Map = new Map(Basemap.CreateOpenStreetMap());
        }

        private void SatelliteMap_Checked(object sender, RoutedEventArgs e)
        {
            if (!isLoad) return;
            MyMapView.Map.Basemap = Basemap.CreateImagery();
            //MyMapView.Map = new Map(Basemap.CreateImageryWithLabels());
        }

        private void LayerListBoxWrap_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (rightClick.IsVisible) rightClick.Visibility = Visibility.Hidden;
            if (mapRightClick.IsVisible) mapRightClick.Visibility = Visibility.Hidden;
        }
    }


}
